from typing import Union
from backend.cews.models import Log, PartVersion, Parts, RepairOrder, RepairOrderPart, RepairOrderPartVersion, StockItem, VersionMaster
import datetime

def update_version_master(vm:VersionMaster,instance:StockItem):
    """ vm.sw_ver = instance.sw_ver
    vm.hw_ver = instance.hw_ver
    vm.update = datetime.datetime.now()
    vm.save()
    return vm """
    vms = VersionMaster.objects.filter(stock_code=instance.stock_code,deleted=False)
    for vm in vms:
        vm.delete()

    swl = instance.sw_ver.split(',')
    hwl = instance.hw_ver.split(',')

    for sw in swl:
        vm = VersionMaster(stock_code=instance.stock_code,deleted=False)
        vm.update = datetime.datetime.now()
        vm.sw_ver = sw
        vm.hw_ver = ''
        vm.save()
    
    for hw in hwl:
        vm = VersionMaster(stock_code=instance.stock_code,deleted=False)
        vm.update = datetime.datetime.now()
        vm.sw_ver = ''
        vm.hw_ver = hw
        vm.save()

    return

def create_version_master(instance:StockItem):
    
    swl = instance.sw_ver.split(',')
    hwl = instance.hw_ver.split(',')
    for sw in swl:
        vm = VersionMaster(stock_code=instance.stock_code,deleted=False)
        vm.hw_ver = ''
        vm.sw_ver = sw
        vm.save()
    
    for hw in hwl:
        vm = VersionMaster(stock_code=instance.stock_code,deleted=False)
        vm.sw_ver = ''
        vm.hw_ver = hw
        vm.save()

    return 
    """ vm.sw_ver = instance.sw_ver
    vm.hw_ver = instance.hw_ver
    vm.save()
    return vm """

def create_part_version(instance:Parts):
    pv = PartVersion(parts=instance)
    pv.sw_ver = instance.sw_ver
    pv.hw_ver = instance.hw_ver
    pv.stock_code = instance.stock_code
    pv.save()
    return pv


def create_repair_order_part_version(repair_order_part:RepairOrderPart):

    ropv = RepairOrderPartVersion(
        repair_order=repair_order_part.repair_order,
        repair_order_part=repair_order_part,
        stock_code=repair_order_part.stock_code,
        sw_ver=repair_order_part.sw_ver,
        hw_ver=repair_order_part.hw_ver,
    )
    ropv.save()
    return ropv


def query_current_latest_version(repair_order:Union[int,RepairOrder]):
    """
        Query current latest version of a repair order part
        
        Return: 
            ```python
            [{
                'repair_order_part_id':r.id,
                'stock_code':r.stock_code,
                'serail_no':r.serial_no,
                'current_sw_version':r.sw_version,
                'current_hw_version':r.hw_version,
                'latest_sw_version':latest_sw_version,
                'latest_hw_version':latest_hw_version,
            }]
            ```
    """
    if isinstance(repair_order,int):
        repair_order = RepairOrder.objects.get(id=repair_order)
        
    rops = repair_order.get_repair_order_part()
    
    rversions = RepairOrderPartVersion.objects.filter(repair_order=repair_order).select_related('repair_order_part')
    
    stock_codes = [
        r.stock_code
        for r in rversions
    ]

    version_dict = VersionMaster.get_version_dict(stock_codes)
    
    ret = []
    
    for r in rversions:
        versions = version_dict.get(r.stock_code)
        latest_sw_version = ''
        latest_hw_version = ''

        if versions:
            latest_sw_version = [v.sw_ver.replace(" ", "") for v in versions]
            latest_hw_version = [v.hw_ver.replace(" ", "") for v in versions]

        has_sw = False
        has_hw = False


        if ',' in r.sw_ver:
            cs = r.sw_ver.split(',')
            print(cs)
            print(latest_sw_version)
            for c in cs:
                if c.replace(" ", "") in latest_sw_version:
                    has_sw = True

        if r.sw_ver.replace(" ", "") in latest_sw_version:
                    has_sw = True

        if ',' in r.hw_ver:
            cs = r.hw_ver.split(',')
            for c in cs:
                if c.replace(" ", "") in latest_hw_version:
                    has_hw = True

        if r.hw_ver.replace(" ", "") in latest_hw_version:
                    has_hw = True

        # if '' in latest_sw_version:
        #     has_sw = True

        # if '' in latest_hw_version:
        #     has_hw = True
        if Parts.objects.filter(stock_code=r.stock_code, serial_no=r.serial_no, deleted=False).exists():
            p = Parts.objects.filter(stock_code=r.stock_code, serial_no=r.serial_no, deleted=False).first()

            ret.append ({
                'repair_order_part_version_id':r.id,
                'repair_order_part_id':r.repair_order_part.id,
                'stock_code':r.stock_code,
                'description':p.description,
                'serail_no':r.serial_no,
                'current_sw_ver':r.sw_ver,
                'current_hw_ver':r.hw_ver,
                'latest_sw_ver':latest_sw_version,
                'latest_hw_ver':latest_hw_version,
                'sw_ver_correct': has_sw,
                'hw_ver_correct': has_hw,
                })
        
    return ret

def soft_delete_version_master(id, user):
    ## not use
    if not user.has_perm('cews.delete_versionmaster'):
        raise ValueError('User has no permission to delete version master.')

    v = VersionMaster.objects.get(pk=id)
    # v.deleted = True
    # v.save()
    v.delete()

    return True